<!DOCTYPE html>
<html lang="en" class="h-full" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paperless-ai Setup</title>
    <script src="https://cdn.tailwindcss.com/3.4.16"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="css/setup.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/dist/tippy.css" />
    <script src="https://unpkg.com/@popperjs/core@2"></script>
    <script src="https://unpkg.com/tippy.js@latest"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/shepherd.js@10.0.1/dist/css/shepherd.css"/>
    <script src="https://cdn.jsdelivr.net/npm/shepherd.js@10.0.1/dist/js/shepherd.min.js"></script>
</head>
<body class="h-full">
    <button id="themeToggle" class="theme-toggle material-button-2">
        <i class="fas fa-moon dark:fas fa-sun"></i>
    </button>

    <div class="min-h-full">
        <nav class="modern-nav">
            <div class="mx-auto max-w-7xl px-6 lg:px-8">
                <div class="flex h-24 items-center justify-between">
                    <div class="flex items-center space-x-6">
                        <img src="/favicon.ico" alt="Paperless AI Logo" style="height: 60px;">
                        <div>
                            <h1 class="text-2xl font-bold">Paperless-AI <small><%= config.PAPERLESS_AI_VERSION %></small></h1>
                            <p class="text-sm text-secondary">Configuration Setup</p>
                        </div>
                    </div>
                </div>
            </div>
        </nav>

        <main class="py-10">
            <div class="mx-auto max-w-3xl px-6 lg:px-8">
                <!-- Progress Bar -->
                <div class="mb-6">
                    <div class="progress-bar">
                        <div class="progress-bar-fill" style="width: 25%"></div>
                    </div>
                </div>

                <!-- Main Form Card -->
                <div class="material-card">
                    <!-- Tab Navigation -->
                    <div class="tab-navigation border-b border-gray-200 mb-6">
                        <nav class="flex flex-wrap gap-2" role="tablist">
                            <button type="button" 
                                    class="tab-button active flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2" 
                                    data-tab="user-tab">
                                <i class="fas fa-user"></i>
                                User Setup
                            </button>
                            <button type="button" 
                                    class="tab-button flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2" 
                                    data-tab="connection-tab">
                                <i class="fas fa-link"></i>
                                Connection
                            </button>
                            <button type="button" 
                                    class="tab-button flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2" 
                                    data-tab="ai-tab">
                                <i class="fas fa-robot"></i>
                                AI Settings
                            </button>
                            <button type="button" 
                                    class="tab-button flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2" 
                                    data-tab="advanced-tab">
                                <i class="fas fa-cog"></i>
                                Advanced
                            </button>
                        </nav>
                    </div>

                    <form id="setupForm" class="space-y-12">
                        <!-- User Settings Tab -->
                        <div id="user-tab" class="tab-content active">
                            <section>
                                <h2 class="section-title">
                                    <i class="fas fa-user"></i>
                                    User Settings
                                </h2>
                                <div class="space-y-6">
                                    <!-- User settings content -->
                                    <div class="form-group">
                                        <label for="username">Username</label>
                                        <input type="text" 
                                               id="username" 
                                               name="username"
                                               class="modern-input"
                                               required>
                                    </div>
                            
                                    <div class="form-group">
                                        <label for="password">Password</label>
                                        <div class="password-input">
                                            <input type="password" 
                                                   id="password" 
                                                   name="password"
                                                   class="modern-input"
                                                   required>
                                            <button type="button" class="password-toggle" data-input="password">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </div>
                                        <div id="password-strength" class="mt-2"></div>
                                    </div>
                            
                                    <div class="form-group">
                                        <label for="confirmPassword">Confirm Password</label>
                                        <div class="password-input">
                                            <input type="password" 
                                                   id="confirmPassword" 
                                                   name="confirmPassword"
                                                   class="modern-input"
                                                   required>
                                            <button type="button" class="password-toggle" data-input="confirmPassword">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </div>
                                        <div id="password-match" class="mt-2"></div>
                                    </div>
                                </div>
                            </section>
                        </div>

                        <!-- Connection Settings Tab -->
                        <div id="connection-tab" class="tab-content hidden">
                            <section>
                                <h2 class="section-title">
                                    <i class="fas fa-link"></i>
                                    Connection Settings
                                </h2>
                                <div class="space-y-6">
                                    <!-- Connection settings content -->
                                    <div class="form-group">
                                        <label for="paperlessUrl" class="flex items-center gap-2">
                                            Paperless-ngx API URL
                                            <button type="button" 
                                                    class="help-btn text-gray-400 hover:text-gray-600 focus:outline-none"
                                                    id="urlHelp">
                                                <i class="fas fa-circle-question"></i>
                                            </button>
                                        </label>
                                        <input type="text" 
                                               id="paperlessUrl" 
                                               name="paperlessUrl"
                                               value="<%= config.PAPERLESS_API_URL %>"
                                               class="modern-input"
                                               placeholder="http://your-paperless-instance:8000"
                                               required>
                                    </div>

                                    <div class="form-group">
                                        <label for="paperlessToken">API Token</label>
                                        <div class="password-input">
                                            <input type="password" 
                                                   id="paperlessToken" 
                                                   name="paperlessToken"
                                                   value="<%= config.PAPERLESS_API_TOKEN %>"
                                                   class="modern-input"
                                                   required>
                                            <button type="button" class="password-toggle" data-input="paperlessToken">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label for="paperlessUsername">Paperless-ngx Username</label>
                                        <input type="text" 
                                               id="paperlessUsername" 
                                               name="paperlessUsername"
                                               value="<%= config.PAPERLESS_USERNAME %>"
                                               class="modern-input"
                                               required>
                                    </div>
                                </div>
                            </section>
                        </div>

                        <!-- AI Settings Tab -->
                        <div id="ai-tab" class="tab-content hidden">
                            <section>
                                <h2 class="section-title">
                                    <i class="fas fa-robot"></i>
                                    AI Configuration
                                </h2>
                                <div class="space-y-6">
                                    <!-- AI Provider Selection -->
                                    <div class="form-group">
                                        <label for="aiProvider">AI Provider</label>
                                        <select id="aiProvider" 
                                                name="aiProvider"
                                                class="modern-input">
                                            <option value="openai" <%= config.AI_PROVIDER === 'openai' ? 'selected' : '' %>>
                                                OpenAI (ChatGPT)
                                            </option>
                                            <option value="ollama" <%= config.AI_PROVIDER === 'ollama' ? 'selected' : '' %>>
                                                Ollama (Local LLM)
                                            </option>
                                            <option value="custom" <%= config.AI_PROVIDER === 'custom' ? 'selected' : '' %>>
                                                Custom
                                            </option>
                                            <option value="azure" <%= config.AI_PROVIDER === 'azure' ? 'selected' : '' %>>
                                                Azure
                                            </option>
                                        </select>
                                    </div>

                                    <!-- OpenAI Settings -->
                                    <div id="openaiSettings" class="provider-settings">
                                        <div class="form-group">
                                            <label for="openaiKey">OpenAI API Key</label>
                                            <div class="password-input">
                                                <input type="password" 
                                                       id="openaiKey" 
                                                       name="openaiKey"
                                                       value="<%= config.OPENAI_API_KEY %>"
                                                       class="modern-input">
                                                <button type="button" class="password-toggle" data-input="openaiKey">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="openaiModel">OpenAI Model</label>
                                            <select id="openaiModel" 
                                                    name="openaiModel"
                                                    class="modern-input">
                                                <option value="gpt-3.5-turbo-0125" <%= config.OPENAI_MODEL === 'gpt-3.5-turbo-0125' ? 'selected' : '' %>>GPT-3.5 Turbo</option>
                                                <option value="gpt-4o" <%= config.OPENAI_MODEL === 'gpt-4o' ? 'selected' : '' %>>GPT-4o</option>
                                                <option value="o3-mini" <%= config.OPENAI_MODEL === 'o3-mini' ? 'selected' : '' %>>o3-mini</option>
                                                <option value="gpt-4o-mini" <%= config.OPENAI_MODEL === 'gpt-4o-mini' ? 'selected' : '' %>>GPT-4o-mini (Best value)</option>
                                            </select>
                                        </div>
                                    </div>

                                    <!-- Ollama Settings -->
                                    <div id="ollamaSettings" class="provider-settings">
                                        <div class="form-group">
                                            <label for="ollamaUrl">Ollama API URL</label>
                                            <input type="text" 
                                                   id="ollamaUrl" 
                                                   name="ollamaUrl"
                                                   value="<%= config.OLLAMA_API_URL %>"
                                                   class="modern-input">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="ollamaModel">Ollama Model</label>
                                            <input type="text" 
                                                   id="ollamaModel" 
                                                   name="ollamaModel"
                                                   value="<%= config.OLLAMA_MODEL %>"
                                                   class="modern-input">
                                        </div>
                                    </div>

                                    <!-- Custom Provider Settings -->
                                    <div id="customSettings" class="provider-settings">
                                        <div class="form-group">
                                            <label for="customBaseUrl">Base URL</label>
                                            <input type="text" 
                                                   id="customBaseUrl" 
                                                   name="customBaseUrl"
                                                   value="<%= config.CUSTOM_BASE_URL %>"
                                                   class="modern-input"
                                                   placeholder="https://api.example.com">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="customApiKey">API Key</label>
                                            <div class="password-input">
                                                <input type="password" 
                                                       id="customApiKey" 
                                                       name="customApiKey"
                                                       value="<%= config.CUSTOM_API_KEY %>"
                                                       class="modern-input">
                                                <button type="button" class="password-toggle" data-input="customApiKey">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="customModel">Model</label>
                                            <input type="text" 
                                                   id="customModel" 
                                                   name="customModel"
                                                   value="<%= config.CUSTOM_MODEL %>"
                                                   class="modern-input"
                                                   placeholder="Enter model name">
                                        </div>
                                    </div>

                                    
                                    <!-- Azure Settings -->
                                    <div id="azureSettings" class="provider-settings">
                                        <div class="form-group">
                                            <label for="azureEndpoint">Endpoint</label>
                                            <input type="text" 
                                                   id="azureEndpoint" 
                                                   name="azureEndpoint"
                                                   value="<%= config.AZURE_ENDPOINT %>"
                                                   class="modern-input"
                                                   placeholder="https://api.example.com">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="azureApiKey">API Key</label>
                                            <div class="password-input">
                                                <input type="password" 
                                                       id="azureApiKey" 
                                                       name="azureApiKey"
                                                       value="<%= config.AZURE_API_KEY %>"
                                                       class="modern-input">
                                                <button type="button" class="password-toggle" data-input="azureApiKey">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="azureDeploymentName">Deployment</label>
                                            <input type="text" 
                                                   id="azureDeploymentName" 
                                                   name="azureDeploymentName"
                                                   value="<%= config.AZURE_DEPLOYMENT_NAME %>"
                                                   class="modern-input"
                                                   placeholder="Enter deployment name">
                                        </div>

                                        <div class="form-group">
                                            <label for="azureApiVersion">API Version</label>
                                            <input type="text" 
                                                   id="azureApiVersion" 
                                                   name="azureApiVersion"
                                                   value="<%= config.AZURE_API_VERSION %>"
                                                   class="modern-input"
                                                   placeholder="Enter API version">
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label for="tokenLimit">Token Limit</label>
                                        <input type="number" 
                                               id="tokenLimit" 
                                               name="tokenLimit"
                                               value="<%= config.TOKEN_LIMIT %>"
                                               class="modern-input"
                                               placeholder="Enter token limit of model">
                                    </div>
                        
                                    <div class="form-group">
                                        <label for="responseTokens">Response Tokens</label>
                                        <input type="number" 
                                               id="responseTokens" 
                                               name="responseTokens"
                                               value="<%= config.RESPONSE_TOKENS %>"
                                               class="modern-input"
                                               placeholder="Enter approximate token amount for the response">
                                    </div>
                                </div>
                            </section>
                        </div>

                        <!-- Advanced Settings Tab -->
                        <div id="advanced-tab" class="tab-content hidden">
                            <section>
                                <h2 class="section-title">
                                    <i class="fas fa-cog"></i>
                                    Advanced Settings
                                </h2>
                                <div class="space-y-6">
                                    <!-- Basic Settings -->
                                    <div class="form-group">
                                        <label for="useExistingData">Use existing Correspondents and Tags?</label>
                                        <select id="useExistingData" 
                                                name="useExistingData" 
                                                class="modern-input">
                                                <option value="no" <%= config.USE_EXISTING_DATA === 'no' ? 'selected' : '' %>>No</option>
                                                <option value="yes" <%= config.USE_EXISTING_DATA === 'yes' ? 'selected' : '' %>>Yes</option>
                                            </select>
                                        </div>
    
                                        <div class="form-group">
                                            <label for="scanInterval">Scan Interval (Cron Format)</label>
                                            <input type="text" 
                                                   id="scanInterval" 
                                                   name="scanInterval"
                                                   value="<%= config.SCAN_INTERVAL %>"
                                                   class="modern-input"
                                                   required>
                                            <p class="help-text">Default: every 30 minutes</p>
                                        </div>
    
                                        <div class="form-group">
                                            <label for="showTags">Process only specific pre tagged documents?</label>
                                            <select id="showTags" 
                                                    name="showTags" 
                                                    class="modern-input">
                                                <option value="no" <%= config.PROCESS_PREDEFINED_DOCUMENTS === 'no' ? 'selected' : '' %>>No</option>
                                                <option value="yes" <%= config.PROCESS_PREDEFINED_DOCUMENTS === 'yes' ? 'selected' : '' %>>Yes</option>
                                            </select>
                                        </div>
    
                                        <!-- Tags Input -->
                                        <div id="tagsInputSection" class="<%= config.PROCESS_PREDEFINED_DOCUMENTS === 'yes' ? '' : 'hidden' %>">
                                            <div class="form-group">
                                                <label for="tagInput">Tags</label>
                                                <div class="tag-input-container">
                                                    <input type="text" 
                                                        id="tagInput" 
                                                        class="modern-input"
                                                        placeholder="Enter a tag and press Enter">
                                                    <button type="button" 
                                                            class="material-button add-tag-btn">
                                                        <i class="fas fa-plus"></i>
                                                        Add
                                                    </button>
                                                </div>
                                                <div id="tagsContainer" class="tags-container">
                                                    <% if (config.TAGS && Array.isArray(config.TAGS) && config.TAGS.length > 0) { %>
                                                        <% config.TAGS.forEach(tag => { %>
                                                            <div class="modern-tag fade-in">
                                                                <span><%= tag %></span>
                                                                <button type="button"><i class="fas fa-times"></i></button>
                                                            </div>
                                                        <% }); %>
                                                    <% } %>
                                                </div>
                                                <input type="hidden" id="tags" name="tags" value="<%= Array.isArray(config.TAGS) ? config.TAGS.join(',') : '' %>">
                                            </div>
                                        </div>
                                        
                                        <!-- AI Tag identification -->
                                        <hr/>
                                        <div class="form-group">
                                            <label for="aiProcessedTag">Add AI-processed tag to documents?</label>
                                            <select id="aiProcessedTag" 
                                                    name="aiProcessedTag" 
                                                    class="modern-input">
                                                <option value="no" <%= config.ADD_AI_PROCESSED_TAG === 'no' ? 'selected' : '' %>>No</option>
                                                <option value="yes" <%= config.ADD_AI_PROCESSED_TAG === 'yes' ? 'selected' : '' %>>Yes</option>
                                            </select>
                                        </div>
    
                                        <div id="aiTagNameSection" class="<%= config.ADD_AI_PROCESSED_TAG === 'yes' ? '' : 'hidden' %>">
                                            <div class="form-group">
                                                <label for="aiTagName">AI-processed Tag Name</label>
                                                <input type="text" 
                                                    id="aiTagName" 
                                                    name="aiTagName"
                                                    value="<%= config.AI_PROCESSED_TAG_NAME || 'ai-processed' %>"
                                                    class="modern-input"
                                                    placeholder="ai-processed">
                                                <p class="help-text">This tag will be added to documents after AI processing</p>
                                            </div>
                                        </div>
                                        
                                        <hr/>
                                        <div class="form-group">
                                            <label for="usePromptTags">Use specific tags in prompt?</label>
                                            <select id="usePromptTags" 
                                                    name="usePromptTags" 
                                                    class="modern-input">
                                                <option value="no" <%= config.USE_PROMPT_TAGS === 'no' ? 'selected' : '' %>>No</option>
                                                <option value="yes" <%= config.USE_PROMPT_TAGS === 'yes' ? 'selected' : '' %>>Yes</option>
                                            </select>
                                        </div>
    
                                        <div id="promptTagsSection" class="<%= config.USE_PROMPT_TAGS === 'yes' ? '' : 'hidden' %>">
                                            <div class="form-group">
                                                <label for="promptTagInput">Prompt Tags</label>
                                                <div class="tag-input-container">
                                                    <input type="text" 
                                                        id="promptTagInput" 
                                                        class="modern-input"
                                                        placeholder="Enter a tag and press Enter">
                                                    <button type="button" 
                                                            class="material-button add-prompt-tag-btn">
                                                        <i class="fas fa-plus"></i>
                                                        Add
                                                    </button>
                                                </div>
                                                <div id="promptTagsContainer" class="tags-container">
                                                    <% if (config.PROMPT_TAGS && Array.isArray(config.PROMPT_TAGS) && config.PROMPT_TAGS.length > 0) { %>
                                                        <% config.PROMPT_TAGS.forEach(tag => { %>
                                                            <div class="modern-tag fade-in">
                                                                <span><%= tag %></span>
                                                                <button type="button"><i class="fas fa-times"></i></button>
                                                            </div>
                                                        <% }); %>
                                                    <% } %>
                                                </div>
                                                <input type="hidden" id="promptTags" name="promptTags" value="<%= Array.isArray(config.PROMPT_TAGS) ? config.PROMPT_TAGS.join(',') : '' %>">
                                                <p class="help-text">These tags will be exclusively used in the AI prompt</p>
                                            </div>
                                        </div>
                                        <hr/>
                                        <div class="form-group">
                                            <label for="disableAutomaticProcessing">Disable automatic processing?</label>
                                            <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                <label class="flex items-start cursor-pointer w-full">
                                                    <input type="checkbox" 
                                                        id="disableAutomaticProcessing" 
                                                        name="disableAutomaticProcessing" 
                                                        class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                        <%= config.DISABLE_AUTOMATIC_PROCESSING === 'yes' ? 'checked' : '' %>>
                                                    <div class="ml-3">
                                                        <div class="flex items-center font-medium">
                                                            <i class="fas fa-tags text-blue-500 mr-2"></i>
                                                            Disable Automatic Processing
                                                        </div>
                                                        <p class="text-sm text-gray-500 mt-1">Determines if the AI will run on its own or every scan is started manually</p>
                                                    </div>
                                                </label>
                                            </div>
                                        </div>
                                        <hr/>
                                        <!-- Limit Functions Section -->
                                        <div class="form-group space-y-4">
                                            <label class="flex items-center gap-2 font-medium">
                                                <i class="fas fa-sliders-h text-blue-500"></i>
                                                Enable/Disable AI Functions
                                            </label>
                                            <p class="text-sm text-gray-500">Select which functions the AI should perform during document analysis</p>
                                            
                                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-2">
                                                <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                    <label class="flex items-start cursor-pointer w-full">
                                                        <input type="checkbox" 
                                                            id="activateTagging" 
                                                            name="activateTagging" 
                                                            class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                            <%= config.ACTIVATE_TAGGING === 'yes' ? 'checked' : '' %>>
                                                        <div class="ml-3">
                                                            <div class="flex items-center font-medium">
                                                                <i class="fas fa-tags text-blue-500 mr-2"></i>
                                                                Tags Assignment
                                                            </div>
                                                            <p class="text-sm text-gray-500 mt-1">Automatically assign relevant tags to documents</p>
                                                        </div>
                                                    </label>
                                                </div>
                                                
                                                <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                    <label class="flex items-start cursor-pointer w-full">
                                                        <input type="checkbox" 
                                                            id="activateCorrespondents" 
                                                            name="activateCorrespondents" 
                                                            class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                            <%= config.ACTIVATE_CORRESPONDENTS === 'yes' ? 'checked' : '' %>>
                                                        <div class="ml-3">
                                                            <div class="flex items-center font-medium">
                                                                <i class="fas fa-user text-blue-500 mr-2"></i>
                                                                Correspondent Detection
                                                            </div>
                                                            <p class="text-sm text-gray-500 mt-1">Identify document senders automatically</p>
                                                        </div>
                                                    </label>
                                                </div>
                                                
                                                <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                    <label class="flex items-start cursor-pointer w-full">
                                                        <input type="checkbox" 
                                                            id="activateDocumentType" 
                                                            name="activateDocumentType" 
                                                            class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                            <%= config.ACTIVATE_DOCUMENT_TYPE === 'yes' ? 'checked' : '' %>>
                                                        <div class="ml-3">
                                                            <div class="flex items-center font-medium">
                                                                <i class="fas fa-file-alt text-blue-500 mr-2"></i>
                                                                Document Type Classification
                                                            </div>
                                                            <p class="text-sm text-gray-500 mt-1">Determine the type of document automatically</p>
                                                        </div>
                                                    </label>
                                                </div>
                                                
                                                <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                    <label class="flex items-start cursor-pointer w-full">
                                                        <input type="checkbox" 
                                                            id="activateTitle" 
                                                            name="activateTitle" 
                                                            class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                            <%= config.ACTIVATE_TITLE === 'yes' ? 'checked' : '' %>>
                                                        <div class="ml-3">
                                                            <div class="flex items-center font-medium">
                                                                <i class="fas fa-heading text-blue-500 mr-2"></i>
                                                                Title Generation
                                                            </div>
                                                            <p class="text-sm text-gray-500 mt-1">Generate meaningful titles for documents</p>
                                                        </div>
                                                    </label>
                                                </div>
    
                                                <div class="modern-card flex-1 p-4 rounded-lg border border-gray-200 hover:border-blue-500 transition-colors duration-200">
                                                    <label class="flex items-start cursor-pointer w-full">
                                                        <input type="checkbox" 
                                                            id="activateCustomFields" 
                                                            name="activateCustomFields" 
                                                            class="mt-1 w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                                            <%= config.ACTIVATE_CUSTOM_FIELDS === 'yes' ? 'checked' : '' %>>
                                                        <div class="ml-3">
                                                            <div class="flex items-center font-medium">
                                                                <i class="fas fa-filter text-blue-500 mr-2"></i>
                                                                Custom Fields
                                                            </div>
                                                            <p class="text-sm text-gray-500 mt-1">Add custom fields to the documents</p>
                                                        </div>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
    
                                        <hr/>
                                        <!-- Custom Fields Section -->
                                        <section>
                                            <div class="form-group space-y-4" id="customFieldsSection">
                                                <label class="flex items-center gap-2 font-medium">
                                                    <i class="fas fa-table text-blue-500"></i>
                                                    Custom Fields Configuration
                                                </label>
                                                <p class="text-sm text-gray-500">Configure custom fields that will be populated by AI during document analysis.</p>
                                                
                                                <!-- Fields Container -->
                                                <div id="customFieldsList" class="space-y-2">
                                                    <% if (config.CUSTOM_FIELDS && Array.isArray(JSON.parse(config.CUSTOM_FIELDS).custom_fields)) { %>
                                                        <% JSON.parse(config.CUSTOM_FIELDS).custom_fields.forEach((field, index) => { %>
                                                            <div class="custom-field-item flex items-center gap-2 p-3 bg-white rounded-lg border border-gray-200 hover:border-blue-200 transition-colors">
                                                                <div class="cursor-move text-gray-400">
                                                                    <i class="fas fa-grip-vertical"></i>
                                                                </div>
                                                                <div class="flex-1 flex items-center gap-4">
                                                                    <div class="flex-1">
                                                                        <p class="font-medium"><%= field.value %></p>
                                                                        <p class="text-sm text-gray-500">
                                                                            Type: <%= field.data_type %>
                                                                            <% if (field.data_type === 'monetary' && field.currency) { %>
                                                                                (<%= field.currency %>)
                                                                            <% } %>
                                                                        </p>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <button type="button" 
                                                                    onclick="removeCustomField(this)" 
                                                                    class="text-gray-400 hover:text-red-500 transition-colors">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </div>
                                                    <% }); %>
                                                <% } %>
                                            </div>

                                            <!-- Add New Field Form -->
                                            <div class="grid grid-cols-12 gap-3 mt-4">
                                                <div class="col-span-6">
                                                    <input type="text" 
                                                        id="newFieldName" 
                                                        class="modern-input w-full" 
                                                        placeholder="Enter field name...">
                                                </div>
                                                
                                                <div class="col-span-2">
                                                    <select id="newFieldType" class="modern-input w-full" onchange="toggleCurrencySelect()">
                                                        <option value="string">Text</option>
                                                        <option value="float">Number</option>
                                                        <option value="integer">Integer</option>
                                                        <option value="monetary">Currency</option>
                                                    </select>
                                                </div>

                                                <div class="col-span-2">
                                                    <select id="currencyCode" class="modern-input w-full" style="display: none;">
                                                        <option value="EUR">EUR</option>
                                                        <option value="USD">USD</option>
                                                        <option value="GBP">GBP</option>
                                                        <option value="JPY">JPY</option>
                                                        <option value="CHF">CHF</option>
                                                        <option value="AUD">AUD</option>
                                                        <option value="CAD">CAD</option>
                                                        <option value="CNY">CNY</option>
                                                        <option value="INR">INR</option>
                                                        <option value="NZD">NZD</option>
                                                    </select>
                                                </div>

                                                <div class="col-span-2">
                                                    <button type="button" 
                                                            onclick="addCustomField()" 
                                                            class="material-button w-full flex items-center justify-center gap-2"
                                                            id="addFieldBtn">
                                                        <i class="fas fa-plus"></i>
                                                        Add
                                                    </button>
                                                </div>
                                            </div>

                                            <!-- Hidden input for form submission -->
                                            <input type="hidden" 
                                                id="customFieldsJson" 
                                                name="customFields" 
                                                value="<%= config.CUSTOM_FIELDS || '{"custom_fields":[]}' %>">
                                        </div>
                                    </section>

                                    <hr/>
                                    <!-- System Prompt -->
                                    <div class="form-group">
                                        <label for="systemPrompt">Prompt Description</label>
                                        <div class="prompt-container">
                                            <textarea id="systemPrompt" 
                                                     name="systemPrompt"
                                                     rows="8"
                                                     class="modern-input"
                                                     placeholder="Describe how the AI should analyze your documents..."><%= config.SYSTEM_PROMPT %></textarea>
                                            <button id="systemPromptBtn" type="button" 
                                                    class="material-button example-btn">
                                                <i class="fas fa-lightbulb"></i>
                                                Example
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </section>
                        </div>

                        <!-- Navigation Buttons -->
                        <div class="flex justify-between pt-6">
                            <button type="button" id="prevBtn" class="material-button" style="display: none;">
                                <i class="fas fa-arrow-left"></i>
                                Previous
                            </button>
                            <button type="button" id="nextBtn" class="material-button">
                                Next
                                <i class="fas fa-arrow-right"></i>
                            </button>
                            <button type="submit" id="submitBtn" class="material-button submit-btn" style="display: none;">
                                <i class="fas fa-save"></i>
                                Save Configuration
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <!-- Scripts -->
    <script src="js/setup.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Initialize textarea newlines -->
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            const systemPromptTextarea = document.getElementById('systemPrompt');
            systemPromptTextarea.value = systemPromptTextarea.value.replace(/\\n/g, '\n');
        });
    </script>

    <!-- Tooltip Script -->
    <script>
        function getTooltipPlacement() {
            return window.innerWidth < 768 ? 'bottom' : 'right';
        }
        
        let tooltipInstance = tippy('#urlHelp', {
            content: `
                <div class="tooltip-content p-2">
                    <h3 class="font-bold text-lg mb-2">API URL Configuration</h3>
                    <p class="mb-2">The URL should follow this format:</p>
                    <code class="block p-2 rounded mb-2">
                        http://your-host:8000
                    </code>
                    
                    <p class="mb-2"><span class="font-semibold">Important Notes:</span></p>
                    <ul class="list-disc pl-4">
                        <li class="mb-1">Must start with <u>http://</u> or <u>https://</u></li>
                        <li class="mb-1">Contains <strong>host/IP</strong> and optionally a <strong>port</strong></li>
                        <li class="mb-1">No additional paths or parameters</li>
                    </ul>

                    <div class="mt-4">
                        <p class="font-semibold mb-1">Docker Network Configuration:</p>
                        <ul class="list-disc pl-4">
                            <li class="mb-1">Using <strong>localhost</strong> or <strong>127.0.0.1</strong> won't work in Docker bridge mode</li>
                            <li class="mb-1">Use your machine's local IP (e.g., <code>192.168.1.x</code>) instead</li>
                            <li class="mb-1">Or use the Docker container name if both services are in the same network</li>
                        </ul>
                    </div>

                    <div class="mt-4">
                        <p class="font-semibold mb-1">Examples:</p>
                        <ul class="list-none space-y-1">
                            <li>🔸 Local IP: <code>http://192.168.1.100:8000</code></li>
                            <li>🔸 Container: <code>http://paperless-ngx:8000</code></li>
                            <li>🔸 Remote: <code>http://paperless.domain.com</code></li>
                        </ul>
                    </div>

                    <p class="mt-4 text-sm italic">The /api endpoint will be added automatically.</p>
                </div>
            `,
            allowHTML: true,
            placement: getTooltipPlacement(),
            interactive: true,
            theme: 'custom',
            maxWidth: 450,
            touch: 'hold',
            trigger: 'mouseenter click',
        });

        window.addEventListener('resize', () => {
            tooltipInstance[0].setProps({ placement: getTooltipPlacement() });
        });
    </script>

    <!-- Initialize tour -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/shepherd.js/dist/js/shepherd.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/shepherd.js/dist/css/shepherd.css"> -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {  
    // Helper function to switch tabs
    function switchToTab(tabId) {
        console.log('Attempting to switch to tab:', tabId);
        const tabButton = document.querySelector(`[data-tab="${tabId}"]`);
        if (tabButton) {
            console.log('Tab button found, clicking');
            const event = new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            });
            tabButton.dispatchEvent(event);
        } else {
            console.warn('Tab button not found:', tabId);
        }
    }

    const tour = new Shepherd.Tour({
        useModalOverlay: true,
        defaultStepOptions: {
            classes: 'shadow-md', // Remove hardcoded background and text colors
            scrollTo: { behavior: 'smooth', block: 'center' },
            cancelIcon: {
                enabled: true
            },
            buttons: [{
                classes: 'shepherd-button-secondary', // Add this class for secondary buttons
                text: 'Exit',
                type: 'cancel'
            }, {
                classes: 'shepherd-button-primary', // Add this class for primary buttons
                text: 'Next',
                type: 'next'
            }],
            popperOptions: {
                modifiers: [{
                    name: 'offset',
                    options: {
                        offset: [0, 12]
                    }
                }]
            }
        }
    });

    console.log('Tour created');

    // Define all tour steps
    const tourSteps = [
        {
            id: 'welcome',
            title: 'Welcome to Paperless-AI Setup',
            text: 'This guided walkthrough will help you configure Paperless-AI, an intelligent automation add-on for Paperless-NGX. Follow the steps carefully to optimize document processing.',
            buttons: [
                {
                    text: 'Skip',
                    action: () => tour.complete()
                },
                {
                    text: 'Start',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('user-tab')
        },
        {
            id: 'user-setup',
            title: 'User Setup',
            text: 'Here, you need to create a user account for Paperless-AI. This user will be used to access and manage the automation processes.',
            attachTo: {
                element: '#user-tab',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('user-tab')
        },
        {
            id: 'api-connection',
            title: 'Paperless-NGX API Connection',
            text: 'Enter the API URL of your Paperless-NGX instance. This is required for the AI to access and process your documents.',
            attachTo: {
                element: '#paperlessUrl',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('connection-tab')
        },
        {
            id: 'api-token',
            title: 'API Token',
            text: 'Provide a valid API Token for authentication. This ensures Paperless-AI can interact securely with Paperless-NGX.',
            attachTo: {
                element: '#paperlessToken',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('connection-tab')
        },
        {
            id: 'paperless-username',
            title: 'Paperless-ngx Username',
            text: 'Specify the username used in Paperless-NGX for API authentication.',
            attachTo: {
                element: '#paperlessUsername',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('connection-tab')
        },
        {
            id: 'ai-provider',
            title: 'AI Provider Selection',
            text: 'Choose an AI provider for document processing. You can use OpenAI (ChatGPT), Ollama (Local LLM), or a custom AI provider.',
            attachTo: {
                element: '#ai-tab',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('ai-tab')
        },
        {
            id: 'existing-data',
            title: 'Use Existing Data',
            text: 'Enable this option to reuse existing Paperless-NGX correspondents and tags for document classification. <br> <b>Note:</b> This will improve AI accuracy and reduce manual corrections. BUT if you have a vast amount of data, it may overload the Token limit.',
            attachTo: {
                element: '#useExistingData',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'scan-interval',
            title: 'Scan Interval',
            text: 'Define the cron schedule for scanning new documents. Adjust this based on your automation needs.',
            attachTo: {
                element: '#scanInterval',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'process-tags',
            title: 'Process only specific tagged documents',
            text: 'Enable this to process only documents with specific tags. This is useful for targeted automation. For example, all documents tagged "invoices" will be processed by AI.',
            attachTo: {
                element: '#showTags',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'ai-processed-tag',
            title: 'AI-Processed Tag',
            text: 'Enable this to mark AI-processed documents with a specific tag (e.g., "ai-processed"). This helps differentiate AI-analyzed files.',
            attachTo: {
                element: '#aiProcessedTag',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'disableAutomaticProcessing',
            title: 'Disable/Enable Automatic Processing',
            text: 'Choose whether the AI should run automatically or only when triggered manually. This can be useful for testing and control.',
            attachTo: {
                element: '#disableAutomaticProcessing',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'ai-tagging',
            title: 'AI Tag Assignment',
            text: 'Enable this feature to allow AI to automatically assign relevant tags to documents based on content analysis.',
            attachTo: {
                element: '#activateTagging',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'correspondent-detection',
            title: 'AI Correspondent Detection',
            text: 'When enabled, AI will attempt to extract the senders name and link it to an existing Paperless-NGX correspondent.',
            attachTo: {
                element: '#activateCorrespondents',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'doc-type-classification',
            title: 'Document Type Classification',
            text: 'This feature allows AI to classify documents automatically, e.g., invoices, contracts, receipts.',
            attachTo: {
                element: '#activateDocumentType',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'title-generation',
            title: 'Title Generation',
            text: 'AI can generate meaningful titles for documents based on their content.',
            attachTo: {
                element: '#activateTitle',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'custom-fields',
            title: 'Custom Fields',
            text: 'AI will try to extract additional metadata fields from documents based on your configuration. </br><b>NOTE:</b> This requires careful setup and testing. Vague or incorrect fields may lead to inaccurate results.',
            attachTo: {
                element: '#activateCustomFields',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'custom-fields-config',
            title: 'Custom Fields Configuration',
            text: 'Here, you can define additional metadata fields that AI should extract from documents.',
            attachTo: {
                element: '#customFieldsSection',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'system-prompt',
            title: 'AI System Prompt',
            text: 'Provide a system prompt that defines how AI should analyze and categorize your documents.',
            attachTo: {
                element: '#systemPrompt',
                on: 'right'
            },
            buttons: [
                {
                    text: 'Next',
                    action: () => tour.next()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        },
        {
            id: 'save-config',
            title: 'Save Configuration',
            text: 'Click "Save Configuration" to apply all your settings and activate Paperless-AI automation.',
            attachTo: {
                element: '.submit-btn',
                on: 'top'
            },
            buttons: [
                {
                    text: 'Finish',
                    action: () => tour.complete()
                }
            ],
            beforeShow: () => switchToTab('advanced-tab')
        }
    ];

    // Add all steps to the tour with error handling
    tourSteps.forEach(step => {
        try {
            console.log('Adding step:', step.id);
            tour.addStep(step);
        } catch (error) {
            console.error(`Failed to add step ${step.id}:`, error);
        }
    });

    // Listen for tour events with proper error handling
    tour.on('show', (evt) => {
        try {
            const currentStep = evt.step;
            console.log('Tour step is being shown:', currentStep.id);
            
            // Execute beforeShow if it exists
            if (currentStep.options.beforeShow) {
                currentStep.options.beforeShow();
            }
            
            // Update progress bar
            const progress = document.querySelector('.progress-bar-fill');
            if (progress) {
                const currentIndex = tour.steps.indexOf(currentStep);
                const percentage = ((currentIndex + 1) / tour.steps.length) * 100;
                progress.style.width = `${percentage}%`;
            }
        } catch (error) {
            console.error('Error in tour show event:', error);
        }
    });

    tour.on('complete', () => {
        try {
            console.log('Tour completed');
            localStorage.setItem('tour_completed', 'true');
        } catch (error) {
            console.error('Error in tour complete event:', error);
        }
    });

    // Start the tour with error handling
    setTimeout(() => {
        try {
            console.log('Starting tour...');
            tour.start();
        } catch (error) {
            console.error('Error starting tour:', error);
        }
    }, 1000);

    // Add restart button with error handling
    try {
        const restartButton = document.createElement('button');
        restartButton.className = 'material-button fixed bottom-4 right-4';
        restartButton.innerHTML = '<i class="fas fa-question-circle"></i> Restart Tour';
        restartButton.onclick = () => {
            try {
                tour.start();
            } catch (error) {
                console.error('Failed to restart tour:', error);
            }
        };
        document.body.appendChild(restartButton);
    } catch (error) {
        console.error('Failed to create restart button:', error);
    }
});
    </script>
</body>
</html>